<template>
  <div class="star-rating">
    <!-- 生成全星 -->
    <span v-for="n in fullStars" :key="`full-${n}`" class="star">&#9733;</span>
    <!-- 生成半星 -->
    <span v-if="hasHalfStar" class="star half-star">&#9733;</span>
    <!-- 生成空星 -->
    <span v-for="n in emptyStars" :key="`empty-${n}`" class="star"
      >&#9734;</span
    >
  </div>
</template>

<script setup>
import { computed } from "vue";

// 接收评分参数，必须是0.5的倍数
const props = defineProps({
  rating: {
    type: Number,
    required: true,
    validator: (value) => value >= 0 && value <= 5 && value % 0.5 === 0,
  },
});

// 计算全星的数量
const fullStars = computed(() => Math.floor(props.rating));
// 判断是否有半星
const hasHalfStar = computed(() => props.rating % 1 >= 0.5);
// 计算空星的数量
const emptyStars = computed(
  () => 5 - fullStars.value - (hasHalfStar.value ? 1 : 0)
);
</script>

<style>
.star-rating {
  display: flex;
  align-items: center;
  font-size: 24px;
  color: gold;
}

.star {
  margin-right: 4px;
}

/* 半星样式 */
.half-star {
  position: relative;
}

.half-star:before {
  content: "\2605"; /* 实心星 */
  position: absolute;
  color: gold;
  width: 50%; /* 只显示一半 */
  overflow: hidden;
}
</style>
